<?php

namespace App\Http\Controllers\Cart;

use App\Http\Controllers\Controller;
use App\Http\Requests\CartPostRequest;
use App\Models\Cart\Cart;
use App\Models\cart\Good;
use App\Models\Cart\SpecGoods;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class CartController extends Controller
{
    /**
     * 购物车展示页
     */
    public function cart(){
        $data = Cart::with(['goods','spec'])->get();
        return view('cart.cart',compact('data'));
    }

    /**
     * @param Request $request
     * @return string
     * 加入购物车
     * user 刘西壮
     *  http://www.2009aqiwei.com/cart
     */
    public function cart_add(Request $request){
        $login = session('login');
        $user_id = 1;
//        if (!$login){
//            return response()->json([
//                'code' => 401,
//                'msg' => '请先登录',
//                'data' => ''
//            ]);
//        }
        $post = $request->post();
        $spec = $post['spec_ys'].'_'.$post['spec_g'];
        $goods = Good::where('id',$post['goods_id'])->first();
        if ($goods->goods_number <= 0){
            return ['code'=>201,'msg'=>'商品已售空','data'=>''];
        }
        $specGoods = SpecGoods::where('value_ids',$spec)->first();
        $first = Cart::where(['user_id'=>$user_id,'goods_id'=>$post['goods_id']])->first();
        $info = [
            'user_id' => $user_id,
            'goods_id' => $post['goods_id'],
            'number' => $post['number'],
            'spec_goods_id' => $specGoods->id
        ];
        if (!$first){
            $create = Cart::create($info);

            Redis::select(5);
            Redis::hset('order',$create->id,json_encode($info));
            if ($create){
                return '添加成功';
            }
        }else{
            if ($first->number >= 10){
                return '每个用户只能购买10件商品';
            }
            $data = [
                'user_id' => $user_id,
                'goods_id' => $post['goods_id'],
                'number' => $first->number + $post['number'],
                'spec_goods_id' => $specGoods->id
            ];
            Redis::select(5);
            Redis::hset('order',$first->id,json_encode($data));
            $res = $first->update([
                'number' => $first->number + $post['number']
            ]);

            return '购物车添加成功';
        }
    }
}
